// src/api/index.js
import axios from 'axios';
import Cookies from 'js-cookie'

//baseURL
const baseURL = process.env.VUE_APP_API_BASE_URL;

// 创建axios实例
const instance = axios.create({
  baseURL: baseURL, // 设置基础URL
  timeout: 10000, // 请求超时时间
  withCredentials: false, 
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么，例如设置Token
    config.headers['Authorization'] = `${Cookies.get('token')}`;
    return config;
  },
  error => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
   if(response.data.code=="unauthorized"){
     window.location.href = '/login'
     return
   }
    // 对响应数据做点什么
    return response;
  },
  error => {
    // 处理响应错误
    return Promise.reject(error);
  }
);

// 封装get请求
export const get = (url, params) => {
  return instance.get(url, { params });
};

// 封装post请求
export const post = async (url, data) => {
  return await instance.post(url, data,{timeout: 90000});
};

// 可以继续封装其他HTTP方法
export const put = (url, data) => {
  return instance.put(url, data);
};

export const deleteRequest = (url, params) => {
  return instance.delete(url, { params });
};